package it.jack.practicertmp;

import android.media.projection.MediaProjection;
import android.util.Log;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @创建者 Jack
 * @创建时间 2022/7/5 20:39
 * @描述 传输层
 */
public class ScreenLive extends Thread {

    private static final String TAG = "RTMP ";
    private String url;
    private MediaProjection                  mediaProjection;
    // 队列
    private LinkedBlockingQueue<RTMPPackage> queue = new LinkedBlockingQueue<>();

    //是否是正在执行
    private boolean isLiving;

    static {
        System.loadLibrary("practicertmp");
    }

    //生产者入口
    public void addPackage(RTMPPackage rtmpPackage) {
        if (!isLiving) {
            return;
        }
        queue.add(rtmpPackage);
    }

    public void startLive(String url, MediaProjection mediaProjection) {
        this.url = url;
        this.mediaProjection = mediaProjection;
        start();
    }

    //发送数据之前需要先建立连接
    private native boolean connect(String url);

    //推流的方法
    private native boolean sendData(byte[] data, int len, long tms, int type);

    @Override
    public void run() {
        isLiving = true;
        if (!connect(url)) {
            Log.i("连接 ", "run: ----------->推送失败");
            return;
        }else{

            Log.i("连接 ", "run: -----------> 成功");
        }

        //创建编码层对象
        VideoCodec videoCodec = new VideoCodec(this);
        videoCodec.startLive(mediaProjection);

        AudioCodec audioCodec = new AudioCodec(this);
        audioCodec.startLive();

        while (isLiving) {
            RTMPPackage rtmpPackage = null; //定义成全局变量更佳
            try {
                rtmpPackage = queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //发送数据
            Log.i(TAG, "取出数据" );
            if (rtmpPackage != null && rtmpPackage.getBuffer() != null && rtmpPackage.getBuffer().length != 0) {
                Log.i(TAG, "run: ----------->推送 "+ rtmpPackage.getBuffer().length);
                sendData(rtmpPackage.getBuffer(), rtmpPackage.getBuffer().length , rtmpPackage.getTms(), rtmpPackage.getType());
            }
        }
    }
}
